<template>
  <div class="container">
    <nav-bar :title="title">
      <!-- <span style="color: #333">
        <svg-icon icon-class="share" :width="15" :height="15" />
      </span> -->
    </nav-bar>
    <template v-for="(item, idx) in purchaseList" >
      <Item
      v-if="item.type != 3"
      :is-show-step="true"
      :index="item.orderCode || item.id+''"
      :num="item.goodsCount"
      :max-num="item.goodsCount"
      :min-number="item.goodsCount"
      :thumb="item.goodsImg"
      :sale-user="item.saleUserName"
      :buy-user="item.buyUserName"
      :title="item.goodsName"
      :price="(item.goodsPrice * item.goodsCount) | yuan"
      :is-checked="item.checked"
      :is-show-checkbox="type==1"
      :disabled="item.saleStatus==3"
      :time="item.addCardTime"
      tag-slot="warehouseTagSlot"
      class="warehouse-card"
      @input="handleItemSelect($event, 'purchase', idx, item.checked)"
    >
      <template name="warehouseTagSlot">
        <van-tag
          v-for="(item, idx) in !item.statusName ? [] : [item.statusName]"
          :key="idx"
          plain
          type="danger"
          style="margin-right: 4px"
          class="mt-12"
        >{{ item }}</van-tag>
      </template>
      
    </Item>
    </template>
    
    <Tabbar :value="isOkList.length == purchaseList.length" v-if="purchaseList && purchaseList.length > 0 && type == 1" :normal-product="normalProduct" slot-name="warehouse" @pay="toPay" @input="handleAllSelect">

      <template name="warehouse">
        <van-button
          v-if="getButtonName"
          :disabled="checkedOption && timeFlag"
          round
          type="info"
          color="linear-gradient(to right, #ff6034, #ee0a24)"
          style="margin-right: 40px;"
          @click="onSubmit"
        >{{ getButtonName
        }}</van-button>
        <!-- <van-button v-if="checkedOption && checkedOption.saleStatus === 3" :disabled="timeFlag" round type="info"
          color="linear-gradient(to right, #ff6034, #ee0a24)" @click="onCalculate">去结算</van-button> -->
      </template>
    </Tabbar>
    <van-dialog
      v-model="showAuditVisible"
      title="确认审核"
      show-cancel-button
      confirm-button-text="审批通过"
      cancel-button-text="审批拒绝"
      @confirm="confirmAudit"
      @cancel="cancelAudit"
    >
      <div
        style="
          width: 100%;
          color: #333;
          display: flex;
          justify-content: center;
          margin-top: 20px;
        "
      >
        商品价格： {{ paymentPrice || 0 }}元
      </div>
      <div
        style="
          display: flex;
          justify-content: center;
          width: 100%;
          height: 200px;
          margin-top: 20px;
        "
      >
        <van-uploader v-model="productUrl" multiple :max-count="1" :after-read="afterRead" preview-size="6.9rem" />
      </div>
    </van-dialog>
    <van-dialog v-model="showPaymentVisible" title="待确认" show-cancel-button @confirm="confirmPay" @cancel="onCancel">
      <div
        style="
          width: 100%;
          color: #333;
          display: flex;
          justify-content: center;
          margin-top: 20px;
        "
      >
      <div class="left" style="width: 100px;text-align: right">商品价格：</div>
      <div class="right">{{ groundingGoodsPrice || 0 }}元</div>
         
      </div>
      <div
        style="
          width: 100%;
          color: #333;
          display: flex;
          justify-content: center;
          margin-top: 20px;
        "
      >
      <div class="left" style="width: 100px;text-align: right">服务费：</div>
      <div class="right">{{ commissionPrice || 0 }}元</div>
      </div>
      <div
        style="
          width: 100%;
          color: #333;
          display: flex;
          justify-content: center;
          margin-top: 20px;
        "
      >
      <div class="left" style="width: 100px;text-align: right">余额：</div>
      <div class="right">{{ balance || 0 }}元</div>
      </div>
      <div
        style="
          width: 100%;
          color: #333;
          display: flex;
          justify-content: center;
          margin-top: 20px;
        "
      >
      <div class="left" style="width: 100px;text-align: right">需支付：</div>
      <div class="right">{{ payPrice || 0 }}元</div>
      </div>
    </van-dialog>
    <!-- <van-dialog v-model="showPaymentVisible" title="去上架" show-cancel-button @confirm="confirmPay">
      <div style="
          width: 100%;
          color: #333;
          display: flex;
          justify-content: center;
          margin-top: 20px;
        ">
        商品价格： {{ paymentPrice || 0 }}元
      </div>

    </van-dialog> -->
  </div>
</template>

<script>
import {
  checkAddReq,
  getCargoPrice,
  getRepositoryData,
  settleCart,
  updatePayAuditRefuse,
  updateWarehouseStatus,
  cgShelvesVerify
  
} from '@/api/cart'
import Item from '@/views/warehouse/modules/Item.vue'
import Tabbar from '@/views/warehouse/modules/Tabbar.vue'
import { updatePayment } from '@/api/cart'
import { base64uploadFile } from '@/api/upload'

export default {
  name: 'WarehouseIndex',
  components: {
    Item,
    Tabbar
  },
  data() {
    return {
      purchaseList: [],
      balance:'',
      title: '',
      recordOption: {},
      showPaymentVisible: false,
      productUrl: [],
      paymentPrice: 0,
      uploader: [],
      urls: '',
      showAuditVisible: false,
      timeFlag: false,
      paymentUrl: '',
      isOkList: [],
      type: 0,
      commissionPrice: 0,
      groundingGoodsPrice: 0,
      payPrice: 0,
      payUrl: '',
      commissionOrderPayNo:'',
      ispay:false
    }
  },
  computed: {
    normalProduct() {
      return this.isOkList[0]?.saleStatus === 3
    },
    checkedOption() {
      return this.purchaseList.find((item) => item.checked)
    },
    getButtonName() {
      console.log(this.isOkList)
      const record = this.isOkList
      // if (!record) {
      //   return
      // }
      let selectStatus = false
      if (!this.isOkList.length) return
      record.forEach(item=>{
        if(item.checked){
          selectStatus = true
        }
      })
      // const buttonsEnum = [
      //   '去付款',
      //   '去上架'
      // ]
      if (selectStatus) {

        return '去确认'
      }
      // const queryParam = this.$route.query;
      // const typeFlag = queryParam.type === "1";
      // const buttonOptions = {
      //   2: typeFlag ? "" : "去审核",
      //   3: typeFlag ? "去上架" : "",
      //   4: typeFlag ? "" : "上架审核",
      // };
      // if (!this.isOkList.length) return
      // return '去上架'
    }
  },
  mounted() {
    // this.getData(this.type)
    console.log(this.getType)
    const type = this.$route.query.type
    const options = {
      1: '买方仓库',
      2: '卖方仓库'
    }
    this.title = options[type]
    this.type = type
    this.getData(type)
  },
  methods: {
    toPay() {
      if(this.isOkList.length>1){
        return this.$toast.fail('采购区商品一次仅能提一件商品')
      }
      this.$dialog.confirm({
        title: '确认去提货？'
      }).then(res => {
        if (res === 'confirm') {
          sessionStorage.setItem('takeGoods', JSON.stringify(this.isOkList))
          let ids = ''
          this.isOkList.forEach((item,index)=>{
            if(index+1!=this.isOkList.length){
              ids += item.id+','
            }else{
              ids += item.id
            }
          })
          console.log('ids',ids)
          this.$router.push({
            path: `/order/confirm?id=${ids}&type=2`
          })
        }
      })
      
    },
    async handleAllSelect(value) {

      if (value) {
        this.purchaseList.forEach((item,index)=>{
          item.checked = true
          this.$set(this.purchaseList,index,item)
        })
        console.log(this.papurchaseList)
        const filterArr = this.purchaseList.filter((item, index) => {
          console.log(item)
          this.purchaseList[index]['indexNum'] = index
          if (item.saleStatus === 3) {
            return true
          }
        })
        console.log(filterArr, this.purchaseList)

        this.$set(this, 'isOkList', filterArr)
        console.log(this.isOkList)
      } else {
        this.purchaseList.forEach((item,index)=>{
          item.checked = false
          this.$set(this.purchaseList,index,item)
        })
        this.$set(this, 'isOkList', [])
      }
    },
    async afterRead(file) {
      this.$toast.loading({
        message: '正在上传...',
        forbidClick: true,
        overlay: true
      })
      // 此时可以自行将文件上传至服务器
      const uploadRes = await base64uploadFile({
        base64content: file.content,
        filename: file.file.name
      })
      this.urls = uploadRes.map.fileName
      this.$toast.clear()
      this.$toast.success('上传图片成功')
    },
    getType() {
      const type = this.$route.query.type
      const options = {
        1: '买方仓库',
        2: '卖方仓库'
      }
      this.title = options[type]
      return type
    },
    async onCalculate() {
      const record = this.recordOption
      await settleCart({ orderId: record.id })
      const type = this.getType()
      this.getData(type)
    },
    async getData(type) {
      const res = await getRepositoryData({ type })
      console.log('仓库订单==', res)
      const purchaseList = res.map.data.map((item) => {
        item.checked = false
        console.log('item.addCardTime:',item.addCardTime)
        console.log('item.groundingTime:',item.groundingTime)
        let date =''
        if(this.$route.query.type == 1){
          date =new Date(item.addCardTime)
        }else{
          date =new Date(item.groundingTime)

        }
        let y = date.getFullYear()
        let M = date.getMonth()>8 ?date.getMonth()+1 : '0'+(date.getMonth()+1)
        let d = date.getDate()>9 ? date.getDate(): '0'+date.getDate()
        let h = date.getHours()>9 ? date.getHours(): '0'+date.getHours()
        let m = date.getMinutes()>9 ? date.getMinutes(): '0'+date.getMinutes()
        let s = date.getSeconds()>9 ? date.getSeconds(): '0'+date.getSeconds()
        item.addCardTime = `${y}-${M}-${d} ${h}:${m}:${s}`
        console.log(item.addCardTime)
        if (!item.saleStatus) {
          return item
        }
        return item
      })
      this.$set(this,'purchaseList',purchaseList)
      console.log(this.purchaseList)
    },
    async handleItemSelect(playload, type, index, checked) {
      // debugger
      console.log(playload, type, index, checked)
      const item = this.purchaseList[index]
      item.checked = !item.checked
      const indexs = this.isOkList.findIndex((item) => {
        return item.id === playload.idx
      })
      console.log(indexs)

      if (this.isOkList.length === 1) {
        this.isOkList = []
        if (playload.val) {
          this.$set(this.isOkList, this.isOkList.length, item)
        }
      } else {
        if (indexs !== -1) {
          this.isOkList.slice(0, indexs)
        } else {
          this.$set(this.isOkList, this.isOkList.length, item)
        }
      }
      console.log(this.isOkList)
      console.log(this.purchaseList)
      this.purchaseList.map((item) => {
        item.index = ''
        item.checked = false
      })
      this.purchaseList[index].index = index
      this.purchaseList[index].checked = !checked
      this.$set(this.purchaseList, index, this.purchaseList[index])
      this.recordOption = {}
      this.timeFlag = false
    },
    async onSubmit() {
      
      if(!this.ispay){
        this.ispay =true
      }else{
        this.ispay =false
        return false
      }
      this.$toast.loading('请求中')
      console.log(this.isOkList)
      if(this.isOkList.length<this.purchaseList.length){
        return this.$toast.fail('上架时必须全选')
      }
      const ids = this.isOkList.map((item) => {
        return item.id
      })

      console.log('ids==', ids)
      const res = await cgShelvesVerify({ orderIds: ids })
      // const res = await checkAddReq({ orderIds: ids })
      console.log(res)
      if (res.code == 200) {
        const data = res.map.data
        this.commissionPrice = data.commissionPrice
        this.balance =data.userBalance
        this.payPrice = data.payPrice
        this.payUrl = data.payUrl
        this.payNo = data.commissionOrderPayNo
        sessionStorage.setItem('orderSn', this.payNo)
        this.groundingGoodsPrice = data.groundingGoodsPrice
        this.showPaymentVisible = true
        this.ispay = false
        console.log(this.showPaymentVisible)
      }
      // this.showPaymentVisible = true
    },
    async confirmAudit() {
      const record = this.recordOption
      await updateWarehouseStatus({
        orderId: record.id,
        currentSaleStatus: record.saleStatus
      })
      const type = this.getType()
      this.getData(type)
    },
    async cancelAudit() {
      const record = this.recordOption
      await updatePayAuditRefuse({ orderId: record.id })
      const type = this.getType()
      this.getData(type)
    },
    onCancel() {
      this.urls = ''
      this.ispay = false
      this.showPaymentVisible = false
    },
    async confirmPay() {
      this.$toast.loading({message:'加载中',duration:5000})
      if(!this.ispay){
        this.ispay =true
      }else{
        this.timer = setTimeout(()=>{
          this.ispay = false
          clearTimeout(this.timer)
          // window.location.reload()
        },20000)
        
        return this.$toast.fail('请勿重复提交！')
      }
      // 上架费为3
      sessionStorage.setItem('orderType', 3)
      sessionStorage.setItem('payRedirct', '/user/order/warehouseList/')
      console.log(this.payUrl)
      if(this.payUrl == '' || this.payUrl == undefined){
        const ids = this.isOkList.map((item) => {
          return item.id
        })
        const res = await checkAddReq({ orderIds: ids })
        this.$toast.clear()

        console.log(res)
        if(res){
          this.$toast.success('上架成功，请前往卖方仓库查看')
          this.getData(this.type)
          this.ispay =true
        }
        
        // return
      }else{
        return this.$toast.fail(`余额不足，请联系店长充值${this.payPrice}`)
        // window.open(this.payUrl)
        // location.href = this.payUrl
        // location.assign(this.payUrl);
        window.open(this.payUrl, '_self');
          const data = this.payUrl
          // this.$router.push('/transfer?src=' + data)
          console.log(data)
          // this.$router.push('/transfer?src=' + data)
          // const newWindow = window.open('', '_self');
    
        
          // 写入数据到新窗口
          // newWindow.document.write(data);
          
          // 如果需要执行数据中的JavaScript代码，可以使用eval()
          // newWindow.document.close(); // 关闭文档，确保所有资源都加载完毕
          // newWindow.eval(newWindow.document.getElementsByTagName('script')[0].innerText);
      }
      // this.$router.push('/transfer?src=' + this.payUrl)
      // window.location.href = this.payUrl


      // this.$router.replace({
      //   name: 'PayStatus',
      //   params: {
      //     orderType: 'procurement',
      //     status: 'pending',
      //     orderNo: -99
      //   }
      // })
    }
    // async confirmPay() {
    //   const record = this.checkedOption;
    //   this.paymentUrl = "/upload/" + record.qrCodeUrl;
    //   if (record) {
    //     await updateWarehouseStatus({
    //       orderId: record.id,
    //       payPicUrl: this.urls,
    //       currentSaleStatus: record.saleStatus,
    //     });
    //     const type = this.getType();
    //     this.getData(type);
    //     this.showPaymentVisible = false;
    //   }
    // },
  }
}
</script>

<style scoped lang="scss">
.container{
  padding-bottom: 120px;
}
.title-bar {
  width: 100%;
  text-align: center;
  font-size: 28px;
  font-weight: bolder;
  margin: 30px 0;
  overflow: hidden;
}

.warehouse-card {
  width: 100%;
  // background-color: #fff;
  box-sizing: border-box;
  overflow: hidden;

  ::v-deep .van-card__title {
    font-size: 30px;
    font-weight: 600;
  }

  .mt-12 {
    margin-top: 12px;
  }

  ::v-deep .van-tag {
    line-height: 38px;
    font-weight: 600;
  }
}
</style>
